package com.msb.juc.c_024;


import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 写时复制容器，Copy on Write
 * 多线程环境下，写时效率低，读时效率高
 * 适合写少读多的环境
 */
public class T02_CopyOnWriteList {
    public static void main(String[] args) {
        /*
        CopyOnWrite
        读时不加锁，写时加锁
        写时会复制一份数组，再加新内容，然后改变原来引用
         */
        List<String> list = new CopyOnWriteArrayList<>();
        Random random = new Random();
        Thread[] threads = new Thread[100];

        for (int i = 0; i < threads.length; i++) {
            Runnable task = new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 1000; j++) {
                        list.add("a" + random.nextInt(10000));
                    }
                }
            };
            threads[i] = new Thread(task);
        }
        runAndComputeTime(threads);
        System.out.println(list.size());

    }

    static void runAndComputeTime(Thread[] threads) {
        long s1 = System.currentTimeMillis();
        Arrays.asList(threads).forEach(thread -> thread.start());
        Arrays.asList(threads).forEach(thread -> {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long s2 = System.currentTimeMillis();
        System.out.println(s2 - s1);
    }
}
